package bin_tree.leetcode;

/**
 * @author shkstart
 * @create 2022-10-25-13:55
 */
public class Num606 {
    StringBuilder sb = new StringBuilder();

    public String tree2str(TreeNode root) {
        if (root == null) {
            return "";
        }
        preOrder(root);

        return sb.toString();
    }
    private void preOrder(TreeNode root){
        if (root == null) {
            return;
        }
        //"1(2(4))(3)
        sb.append(root.val);
        if(root.left!=null){
            sb.append("(");
            //先序遍历左树
            preOrder(root.left);
            sb.append(")");
        }else{
//            左空，判断右树是否为空
            if(root.right != null){
                sb.append("()");
            }
        }
        if(root.right!=null){
            sb.append("(");
            preOrder(root.right);
            sb.append(")");
        }
    }
}
